#include "polar_matrix.h"
#include "bmp_writer.h"
#include <fstream>
#include <cassert>

#define HELP "uso: " << argv[0] << " [-i <input_file>=sol1.pm] -o <output_file> [-v] [-t]" << endl

char locate_option(char** options, char options_size, char* str);

using namespace std;
int verbose= 0;

int main(int argc, char* argv[]) {
	char* input_file= NULL;
	char* output_file= NULL;
 	char* options[]= {"-i", "-o", "-v", "-t"}; 
	char options_size= 4;
	bool only_translate= 0;

	enum OptionType {
		  INPUT_FILE= 0,
			OUTPUT_FILE= 1,
			VERBOSE= 2,
			ONLY_TRANSLATE= 3,
			OPTION_NOT_RECOGNIZED
	}; 

	for(int i= 1; i< argc; i++) {
		char option= locate_option(options, options_size, argv[i]);
		switch(option) {
		case INPUT_FILE:
			input_file= argv[i+1];
			break;
		case OUTPUT_FILE:
			output_file= argv[i+1];
			break;
		case VERBOSE:
			verbose= 1;
			break;
		case ONLY_TRANSLATE:
			only_translate= 1;
			break;
		}
	} 
	
	if(input_file == NULL) 
		input_file= "sol1.pm";
	
	ifstream in(input_file);

	ofstream o;
	if(only_translate) {
		o.open(output_file);	
		if(!o.good()) {
			cerr << "No se puede abrir el archivo " << input_file << endl;
			cerr << HELP;
			return 1;
		}

	}

	if(!in.good()) {
		cerr << "No se puede abrir el archivo " << input_file << endl;
		cerr << HELP;
		return 1;
	}

	double min_value, max_value; 
	ifstream s_conf("conf.txt");
	s_conf >> min_value >> max_value;	
	assert(min_value < max_value);

	PolarMatrix p;
	ifstream s_p_matrix(input_file);
 	s_p_matrix >> p; 
 	s_p_matrix.close(); 
 	Matrix m; 
 	p.toCartesianMatrix(m, 200, 200); 

	if(only_translate) {
		ofstream o(output_file);
		o << m;
		o.close();
	} else {
    BMPWriter b;  
      
    b.saveBMP(m, output_file, min_value, max_value);  
	}

	return 0;
}


char locate_option(char** options, char options_size, char* str) {
	for(int i= 0; i<options_size; i++) {
		if(strcmp(options[i], str) == 0)
			return i;
	}

	return options_size+1;
}
